package com.suray.wcs.service.system.scheduled;

import com.google.common.collect.Lists;
import com.suray.basic.wcs.path.core.Node;
import com.suray.commin.core.utils.SpringContextHolder;
import com.suray.wcs.service.enums.TaskStatus;
import com.suray.wcs.service.enums.WmsTaskStatus;
import com.suray.wcs.service.system.entity.NodeDB;
import com.suray.wcs.service.system.entity.TaskDB;
import com.suray.wcs.service.system.service.ITaskDBService;
import com.suray.wcs.service.system.service.impl.DeviceManagerServiceImpl;
import com.suray.wcs.service.system.service.impl.NodeDBServiceImpl;
import com.suray.wcs.service.wmsconnect.ReturnMsgDevice;
import com.suray.wcs.service.wmsconnect.TaskStatusRtn;
import com.suray.wcs.service.wmsconnect.ToWms;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 定时上报任务
 */
@Component("ToWmsTsk")
public class ToWmsTask {
    private Logger logger = LoggerFactory.getLogger(ToWmsTask.class);

    /**
     * 定时上报任务信息
     */
    public void TaskExeRtnThread(){
        try {
            //获取bean
            ToWms toWms = SpringContextHolder.getBean(ToWms.class);
            ITaskDBService taskDBService = SpringContextHolder.getBean(ITaskDBService.class);
            NodeDBServiceImpl nodeDBService = SpringContextHolder.getBean(NodeDBServiceImpl.class);

            List<TaskDB> taskDBList = taskDBService.getAllNoCommitToWmsTask();
            if(CollectionUtils.isNotEmpty(taskDBList)){
                for(TaskDB taskdb : taskDBList){
                    NodeDB nodeDBEnd = nodeDBService.getNodeDB(Node.parseGrid(taskdb.getEndNodeStr()));
                    //执行任务
                    toWms.executionPhase(TaskStatusRtn.buildTaskStatusRtn(taskdb.getWmsTaskId(), nodeDBEnd.getGridId(), WmsTaskStatus.FINISH));
                }
            }
        } catch (Exception e) {
            logger.error("向wms上报任务状态任务执行失败: " + e.getLocalizedMessage());
        }
    }

    /**
     * 定时上报设备信息
     */
    public void SendDeviceStatusThread(){
        try {
            ToWms toWms = SpringContextHolder.getBean(ToWms.class);
            //获取bean
            DeviceManagerServiceImpl deviceManagerServiceImpl = SpringContextHolder.getBean(DeviceManagerServiceImpl.class);
            //执行任务
            List<ReturnMsgDevice> devices = Lists.newArrayList();
            deviceManagerServiceImpl.fillDevicesIdNullTypeNull(devices,null);
            toWms.deviceStatus(devices);
        } catch (Exception e) {
            logger.error("SendDeviceStatusThread执行失败: " + e.getLocalizedMessage());
        }
    }

}
